package com.rambo.sdh.dao.impl;

import com.rambo.sdh.dao.inter.UserDao;
import com.rambo.sdh.dao.pojo.RolePO;
import com.rambo.sdh.dao.pojo.UserPO;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.object.SqlQuery;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDaoImpl implements UserDao {

	@Autowired
	private SessionFactory sessionFactory;

	public Session getSession() {
		return sessionFactory.getCurrentSession();

	}

	public List<UserPO> getUserList() {
		Session session = this.getSession();
		String sql = "select * from userpo";
		Query query = session.createSQLQuery(sql).addEntity(UserPO.class);
		return query.list();
	}

	@Override
	public UserPO getByKey(Integer id) {
		Session session = this.getSession();

		String sql = "select * from userpo where id=?";
		Query query = session.createSQLQuery(sql).setInteger(0, id);

		return (UserPO) query.list();
	}

	@Override
	public UserPO add(UserPO userPo) {
		Session session = this.getSession();

		session.save(userPo);

		return userPo;

	}

	@Override
	public UserPO edit(UserPO user) {
		Session session = this.getSession();
		session.update(user);
		return user;
	}

	@Override
	public int deleteByKey(Integer id) {
		Session session = this.getSession();
		String sql = "delete from userpo where id=?";
		Query query = session.createSQLQuery(sql).setInteger(0, id);
		int i = query.executeUpdate();
		return i;
	}

	@Override
	// 根据userid得到role
	public List<RolePO> getRolePOByUserId(Integer id) {
		Session session = this.getSession();
		String sql = "select r.*  from userpo u,user_role ur,rolepo r where  u.id=ur.userid and ur.roleid=r.ID and u.id=?";

		Query query = session.createSQLQuery(sql).addEntity(RolePO.class)
				.setInteger(0, id);

		return query.list();
	}

	@Override
	public List<UserPO> getUserPOByRoleId(Integer id) {
		Session session = this.getSession();

		String sql = "select u.*  from  rolepo r ,user_role ur, userpo u where r.id=ur.roleid and ur.userid=u.id and r.id=?";

		Query query = session.createSQLQuery(sql).addEntity(UserPO.class)
				.setInteger(0, id);
		List<UserPO> userPOs=query.list();
		return userPOs;
	}

}
